using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Threading;
using RevitCopilot.Services;

namespace RevitCopilot.ViewModels;

public class StartUpViewModel : INotifyPropertyChanged
{
    private readonly SocketService _socketService;
    private readonly DispatcherTimer _statusTimer;
    private bool _isServerRunning;
    private int _connectedClientsCount;
    private string _serverStatus;

    public StartUpViewModel(SocketService socketService)
    {
        _socketService = socketService;

        // 初始化状态
        IsServerRunning = _socketService.IsRunning;
        ServerStatus = IsServerRunning ? "服务器运行中，等待客户端连接..." : "服务器已停止";
        ConnectedClientsCount = _socketService.GetConnectedClientsCount();

        // 创建定时器，定期更新状态信息
        _statusTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(2)
        };
        _statusTimer.Tick += StatusTimer_Tick;
        _statusTimer.Start();
    }

    private void StatusTimer_Tick(object sender, EventArgs e)
    {
        // 更新服务器状态信息
        IsServerRunning = _socketService.IsRunning;
        ConnectedClientsCount = _socketService.GetConnectedClientsCount();

        if (IsServerRunning)
        {
            ServerStatus = ConnectedClientsCount > 0
                ? "服务器运行中，已连接客户端"
                : "服务器运行中，等待客户端连接...";
        }
        else
        {
            ServerStatus = "服务器已停止";
        }
    }

    public bool IsServerRunning
    {
        get => _isServerRunning;
        set
        {
            if (_isServerRunning != value)
            {
                _isServerRunning = value;
                OnPropertyChanged();
            }
        }
    }

    public int ConnectedClientsCount
    {
        get => _connectedClientsCount;
        set
        {
            if (_connectedClientsCount != value)
            {
                _connectedClientsCount = value;
                OnPropertyChanged();
            }
        }
    }

    public string ServerStatus
    {
        get => _serverStatus;
        set
        {
            if (_serverStatus != value)
            {
                _serverStatus = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // 清理资源，停止定时器
    public void Cleanup()
    {
        if (_statusTimer != null && _statusTimer.IsEnabled)
        {
            _statusTimer.Stop();
        }
        
        // 停止服务器
        if (_socketService != null && _socketService.IsRunning)
        {
            _socketService.Stop();
        }
    }
}